package com.hemi.rhet;

import java.io.IOException;
import java.util.HashMap;

import org.androidpn.client.ServiceManager;
import org.apache.http.client.ClientProtocolException;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;

import com.hemi.rhet.html.TopicList;
import com.hemi.rhet.util.ApplicationContext;
import com.hemi.rhet.util.HttpUtil;
import com.hemi.rhet.util.OSInfoUtil;

public class ActivityTopicMain extends Activity {
	private static final int reply_call_carema = 100;
	private WebView mWebView;
	private String defaultUrl = HttpUtil.buildUrl("/post/new");

	private boolean isCreate = false;
	protected Dialog onCreateDialog(int id) {
		return super.onCreateDialog(id);
	}

	private Handler mHandler = new Handler();
	private static final int SCTU = Menu.FIRST;
	private static final int FB = Menu.FIRST + 1;
	private static final int BACK_ID = Menu.FIRST + 3;
	private static final int FROM_ALARM = Menu.FIRST + 5;
	ServiceManager serviceManager =null;
	public void onCreate(Bundle icicle) {
		OSInfoUtil.version4Adapter();
		super.onCreate(icicle);
		setContentView(R.layout.web_post);
		     serviceManager = new ServiceManager(this);
	     serviceManager.setNotificationIcon(R.drawable.notification);
	     serviceManager.startService();
	       
		mWebView = (WebView) findViewById(R.id.postdispalyview);
		WebSettings webSettings = mWebView.getSettings();
		webSettings.setDefaultTextEncodingName("utf-8");
		webSettings.setSavePassword(false);
		webSettings.setSaveFormData(false);
		webSettings.setJavaScriptEnabled(true);
		webSettings.setSupportZoom(false);
		webSettings.setBuiltInZoomControls(false);
		mWebView.setWebChromeClient(new MyWebChromeClient());
		mWebView.setInitialScale(100);// 初始显示比例100%
		mWebView.setMinimumHeight(100);
		mWebView.setMinimumWidth(100);
		JavaScriptInterfaceBinder.INSTANCE.addCallCaremaAblity(this, mWebView,
				mHandler);
		JavaScriptInterfaceBinder.INSTANCE.addWebDataPostAblity(this, mWebView,
				mHandler);
		JavaScriptInterfaceBinder.INSTANCE.addWebDataUrlRedirectAblity(this,
				mWebView, mHandler);
		JavaScriptInterfaceBinder.INSTANCE.addWebImageSelectAblity(this,
				mWebView, mHandler);
		JavaScriptInterfaceBinder.INSTANCE.addShowTopicDetailAblity(this,
				mWebView, mHandler);
		mWebView.addJavascriptInterface(new JavaScriptInterface2HiddenProcessBar(), "hiddenProcessBar");   
//		 mWebView.loadDataWithBaseURL(null, TopicList.createNew().compile(this, ""), "text/html", "utf-8", null);   
		isCreate = true;
		   new ShowTopicList().execute();
//		mWebView.loadUrl(HttpUtil.buildUrl(this.getTabActionUrl()));
	}

	public String getTabActionUrl() {
		return "/post/allPostes";
	}
	public void hiddenProcess(){
		if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
      		 mLoadingDialog.dismiss();
      		 mLoadingDialog = null;
      	 }
	}
	 class JavaScriptInterface2HiddenProcessBar {
	        public void clickOnAndroid() {   
	        	hiddenProcess();
	        }   
	    }
	  private ProgressDialog mLoadingDialog;

@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(serviceManager!=null )
		serviceManager.stopService();
	}
private class ShowTopicList extends AsyncTask<Void, Void, Object> {
  
    @Override
    protected void onPreExecute() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.setMessage("加载中...");
        }else{
	       	 mLoadingDialog = new ProgressDialog(ActivityTopicMain.this);
	       	 mLoadingDialog.setCancelable(false);
	       	 mLoadingDialog.setMessage("加载中...");
	         mLoadingDialog.show();
        }
    }
    @Override
    protected Object doInBackground(Void... params) {
 	   String urlStr = new StringBuffer(ApplicationContext.DOMAIN+"/post/allPostes_4json").toString();
 			try {
 				HashMap mapparams=  new HashMap();
 				String  content = HttpUtil.postUrl(urlStr, mapparams);
 				String data=TopicList.createNew().compile(ActivityTopicMain.this,"posteList.template", content);
 				return data;
 			} catch (ClientProtocolException e) {
 				e.printStackTrace();
 				return e;
 			} catch (IOException e) {
 				e.printStackTrace();
 				return e;
 			}finally{
 			}
    }
    @Override
    protected void onPostExecute(Object result) { 
        if(result!=null &&	(result instanceof String))
        {
        	mWebView.loadDataWithBaseURL("file:///android_asset/.", result.toString(), "text/html", "utf-8", null);  
        }else if(result instanceof Exception){ 
      	  	Toast.makeText(ActivityTopicMain.this, "数据加载失败！！",Toast.LENGTH_SHORT).show();            
      	  	hiddenProcess();
		  } 
    }
    
 
}


	@Override
	protected void onResume() {
		super.onResume();
		if(isCreate)
		{
			isCreate=false;
		}else{
			// new ShowTopicList().execute();
			
		}
//		mWebView.loadUrl(HttpUtil.buildUrl(this.getTabActionUrl()));
		
//		mWebView.loadDataWithBaseURL(null, TopicList.createNew().compile(this, ""), "text/html", "utf-8", null);   
	}

	public void refresh(){
		// new ShowTopicList().execute();
//		mWebView.loadUrl(HttpUtil.buildUrl(this.getTabActionUrl()));
		
//		mWebView.loadDataWithBaseURL(null, TopicList.createNew().compile(this, ""), "text/html", "utf-8", null);   
		
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		//new ShowTopicList().execute();
//		mWebView.loadUrl(HttpUtil.buildUrl(this.getTabActionUrl()));
		
//		mWebView.loadDataWithBaseURL(null, TopicList.createNew().compile(this, ""), "text/html", "utf-8", null);   
		
//		if (data == null) {
//			ParamUtil.showMessage(ActivityTopicMain.this, "无图片选择！");
//			return;
//		}
//		String message = (String) data.getExtras().get("imageInfo");
//		String imageContainerId = (String) getIntent().getExtras().get("imageContainerId");
//		String fileIdItemName = (String) getIntent().getExtras().get("fileIdItemName");
//		HashMap ham = ParamUtil.stringTomsgMap(message);
//		mWebView.loadUrl("javascript:createImageSrc('" + ham.get("fileId")
//				+ "','" + ham.get("fileName") + "','" + imageContainerId
//				+ "','" + fileIdItemName + "')");
	}

//	@Override
//	public void onAttachedToWindow() {
//		super.onAttachedToWindow();
//		openOptionsMenu();
//	}

	/**
	 * Provides a hook for calling "alert" from javascript. Useful for debugging
	 * your javascript.
	 */
	final class MyWebChromeClient extends WebChromeClient {
		@Override
		public boolean onJsAlert(WebView view, String url, String message,
				JsResult result) {
			result.confirm();
			return true;
		}

	}
}
